package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.utlis.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("login")
    public Result login(@RequestBody User user){
        User dbone = userService.getOne(Wrappers.lambdaUpdate(User.class).eq(User::getName, user.getName()));
        if(dbone==null){
            return Result.fail("没有该用户名");
        }
        if(!dbone.getPassword().equals(DigestUtil.md5Hex(user.getPassword()+dbone.getSalt()))){
            return Result.fail("密码错误");
        }
        redisTemplate.opsForValue().set(dbone,"dbone",30, TimeUnit.MINUTES);
        String token = JWT.create()
                .setPayload("user", dbone)
                .setSigner(JWTSignerUtil.none())
                .sign();
        return Result.success(token);
    }
}
